package com.zzhua.config;

import com.zzhua.pojo.User;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
public class SessionController {

    @Autowired
    SessionDAO sessionDAO;

    @RequiresRoles("role:admin")
    @RequestMapping("stopSession/{sessionId}")
    public String stopSession(@PathVariable("sessionId") String sessionId) {
        Session session = sessionDAO.readSession(sessionId);
        if (session == null) {
            return "未找到该会话";
        }
        Object principals = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        String uname = "";
        if (principals != null) {
            Object user = ((PrincipalCollection) principals).getPrimaryPrincipal();
            uname = ((User) user).getName();
        }
        sessionDAO.delete(session);
        return "停用会话id:"+session.getId()+",用户为: " + uname;
    }

    @RequiresRoles("role:admin")
    @RequestMapping("getAllSessions")
    public List<String> getAllSessions() {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        List<String> nameList = new ArrayList<>();
        sessions.stream().forEach(session -> {
            Object principals = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (principals != null) {
                Object user = ((PrincipalCollection) principals).getPrimaryPrincipal();
                String uname = ((User) user).getName();
                nameList.add(uname);
            }
        });
        return nameList;
    }

}
